import {Lose} from './tips/lose'
import { Win } from './tips/win';
export class Main {
    constructor() {
        // 初始化变量
        this.canvas = wx.createCanvas();
        this.context = this.canvas.getContext('2d');
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        this.gameOver = false;
        this.countNum = 0;
        this.updating = true;

        this.backgroundImage1 = wx.createImage();
        this.backgroundImage1.src = '/images/test.gif';

        this.backgroundImage2 = wx.createImage();
        this.backgroundImage2.src = '/images/test1.png';

        // 玩家和方块的属性
        this.player = {
            x: 50,
            y: this.height / 4,
            width: 30,
            height: 30,
            speedY: 0.05,
            isMovingRight: false
        };

        this.blocks = [];
        for (let i = 0; i < 20; i++) {
            let backgroundImage = (i % 2 === 0) ? this.backgroundImage1 : this.backgroundImage2;
            this.blocks.push({
                x: 200,
                y: i * 40,
                width: 80,
                height: 40,
                backgroundImage: backgroundImage,
                speedX: 0,
                speedY: 0,
                hasCollided: false,
                angle: 0,
                angleOffset: 0
            });
        }

        // 初始化游戏场景
        this.init();
    }

    init() {
        // 监听点击事件
        wx.onTouchStart(() => {
            this.player.isMovingRight = true;
        });
        this.update(); // 开始游戏主循环
    }

    drawBlock(block) {
        this.context.save();
        this.context.translate(block.x + block.width / 2, block.y + block.height / 2);
        this.context.rotate(block.angle);
        this.context.translate(-block.width / 2, -block.height / 2);
        this.context.drawImage(block.backgroundImage, 0, 0, block.width, block.height);
        this.context.restore();
    }

    update() {
        if ( this.isUpdating  === false && this.gameOver === true) {
            this.showLosePopup(); // 显示失败弹窗
            return;
        }
        this.checkGameOver();
        // 更新玩家位置
        if (!this.player.isMovingRight) {
            this.player.y += this.player.speedY;
            if (this.player.y <= 0 || this.player.y + this.player.height >= this.height) {
                this.player.speedY = -this.player.speedY;
            }
        } else {
            this.player.x += 5;
            if(this.player.x >= this.width) //不能出手机边界
            {       
                this.player.x = 50;
                this.player.y = this.height / 2;
                this.player.isMovingRight = false;
            }
        }

        // 更新方块位置
        this.blocks.forEach(block => {
            block.x += block.speedX;
            block.y += block.speedY;
            block.speedY += 0.1;

            if (block.angle !== 0) {
                this.context.save();
                this.context.translate(block.x + block.width / 2, block.y + block.height / 2);
                this.context.rotate(block.angle);
                this.context.translate(-block.width / 2, -block.height / 2);
                this.context.drawImage(block.backgroundImage, 0, 0, block.width, block.height);
                this.context.restore();
            }
        });

        // 检测方块碰撞
        this.blocks.forEach((block, index) => {
            this.blocks.forEach((otherBlock, otherIndex) => {
                if (index !== otherIndex && this.checkCollision(block, otherBlock)) {
                    if (block.speedY > 0 && block.y + block.height <= otherBlock.y + otherBlock.height) {
                        block.y = otherBlock.y - block.height;
                        block.speedY = 0;
                    }
                }
            });

            if (block.y + block.height > this.height) {
                block.y = this.height - block.height;
                block.speedY = 0;
            }
        });

        // 检测玩家与方块的碰撞
        let collidedBlocks = [];
        this.blocks.forEach(block => {
            if (this.checkCollision(this.player, block)) {
                collidedBlocks.push(block);
            }
        });

        if (collidedBlocks.length > 0) {
            this.handleCollision(collidedBlocks);
        }

        this.render();
        requestAnimationFrame(this.update.bind(this));
    }

    render() {
        this.context.clearRect(0, 0, this.width, this.height);
        this.context.fillStyle = 'blue';
        this.context.fillRect(this.player.x, this.player.y, this.player.width, this.player.height);

        this.blocks.forEach((block, index) => {
           this.context.fillStyle = (index % 2 === 0) ? 'pink' : 'green';
            this.drawBlock(block);
        });
    }

    checkGameOver() {
        this.countNum = 0;
        this.blocks.forEach((block,index) => { //检查当前偏移方块数
            if (block.angle !== 0) {
                this.countNum += 1;
            }
            if(this.countNum > 2) {
                
                wx.navigateToScene();
            }
        })
    }

    checkCollision(rect1, rect2) {
        return rect1.x < rect2.x + rect2.width &&
            rect1.x + rect1.width > rect2.x &&
            rect1.y < rect2.y + rect2.height &&
            rect1.y + rect1.height > rect2.y;
    }

    handleCollision(collidedBlocks) {
        if (collidedBlocks.length === 1) {
            let block = collidedBlocks[0];
            if (block.angle === 0 || (block.angle !== 0 && this.countNum === 1)) {
                this.player.isMovingRight = false;
                block.angle = 0;    //bug修复
                block.speedX = 5;

                this.blocks.forEach(b => {
                    if (b.y < block.y) {
                        b.speedY = 2;
                    }
                });
            } else {
                // wx.showLoading({
                //     title: "游戏结束啦，你行不行！",
                //     success: () => {
                //         this.gameOver = true;
                //     }
                // });
                this.isUpdating = false
                this.gameOver = true

                // wx.navigateToScene();
            }
        } else if (collidedBlocks.length === 2) {
            const [block1, block2] = collidedBlocks;
            this.player.isMovingRight = false;

            if (block1.angle === 0 && block2.angle === 0) {
                block1.angle = -Math.PI / 24;
                block2.angle = Math.PI / 24;
            } else if (block1.angle !== 0 || block2.angle !== 0) {
                if (block1.angle !== 0 && block2.angle !== 0) {
                    // wx.showLoading({ //修改为弹窗
                    //     title: "游戏结束啦，你行不行！",
                    //     success: () => {
                    //         this.gameOver = true;
                    //     }
                    // });
                    this.isUpdating = false
                    this.gameOver = true
                    // wx.navigateToScene();
                } else {
                    block1.angle = 0;
                    block2.angle = 0;
                }
            }

            this.blocks.forEach(b => {
                if (b.y < block1.y || b.y < block2.y) {
                    b.angleOffset = Math.random() * 0.02 - 0.01;
                }
            });
            this.blocks.forEach(b => {
                if (b.y < block1.y || b.y < block2.y) {
                    b.speedY = 0;
                }
            });
        }

        this.blocks.forEach(b => b.hasCollided = false);
        this.player.x = 50;
        this.player.y = this.height / 2;
    }
    showLosePopup() {
        this.updating = false; // 停止更新
        // 禁用触摸事件
        wx.offTouchStart();        
        // 创建 Lose 类实例，并传入当前 Canvas 的上下文和尺寸，以及重新开始的回调函数
        // let losePopup = new Lose(this.canvas, this.width, this.height, this.restartGame.bind(this));
        // losePopup.drawPopup(); // 绘制并显示弹窗
        let winPopup = new Win(this.canvas, this.width, this.height);
        winPopup.drawPopup();
    }
    restartGame() {
        this.updating = true; // 恢复更新
        this.gameOver = false;

        // 可以在这里处理重新初始化游戏状态等操作
        this.init();
    }
}
